package com.gtenacg.cartoonservice.util;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class JsoupUtil {

    private static String baseUrl;

    private JsoupUtil() {}

    @Value("${my-config.fileServer.baseUrl}")
    private String tempBaseUrl;

    @PostConstruct
    public void setBaseUrl() {
        baseUrl = this.tempBaseUrl;
    }

    public static List<String> getFolderList(String src) {
        List<String> ChapterList = new ArrayList<>();
        try {
            Document document = Jsoup.connect(src.replace("/filePath",baseUrl)).get();
            Elements aList = document.getElementsByTag("a");
            for (Element aEl : aList) {
                String text = aEl.text();
                if (text.equals("../")) continue;
                if (text.endsWith("/")) {
                    ChapterList.add(text.replaceAll("/",""));
                }
            }

        } catch (IOException e) {
            if (e.getMessage().equals("Connection refused: no further information")) {
                log.error("无法连接指定地址（文件服务器），地址为 \"{}\"", baseUrl + src);
            }
        }

        return ChapterList;
    }

    public static List<String> getFileList(String src) {
        List<String> ChapterInfo = new ArrayList<>();
        try {
            Document document = Jsoup.connect(src.replace("/filePath",baseUrl)).get();
            Elements aList = document.getElementsByTag("a");
            for (Element aEl : aList) {
                String text = aEl.text();
                if (text.equals("../") || text.startsWith("cover")) continue;
                ChapterInfo.add(text);
            }

        } catch (IOException e) {
            if (e.getMessage().equals("Connection refused: no further information")) {
                log.error("无法连接指定地址（文件服务器），地址为 \"{}\"", baseUrl + src);
            }
        }

        return ChapterInfo;
    }
}
